<?php
/**
 * Created by PhpStorm.
 * User: Bostin
 * Date: 2019-02-15
 * Time: 10:25
 */

namespace Bostin\Translator\Sdk;


use GuzzleHttp\Client;

/**
 * Class Yeekit
 * @package Bostin\Translator\Sdk
 */
class Yeekit
{
    /**
     * @var string
     */
    protected $api = 'http://api.yeekit.com/dotranslate.php';

    /**
     * @var
     */
    protected $client;

    /**
     * @var string
     */
    protected $appKid;

    /**
     * @var string
     */
    protected $appKey;

    /**
     * @var array
     */
    protected $config;

    /**
     * Yeekit constructor.
     * @param string $appKid
     * @param string $appKey
     * @param array $config
     */
    public function __construct(string $appKid, string $appKey, array $config = [])
    {
        $this->appKid = $appKid;
        $this->appKey = $appKey;
        $this->config = $config;
    }

    /**
     * @return Client
     */
    private function getClient(): Client
    {
        if (is_null($this->client)) {
            $this->client = new Client($this->config['guzzle'] ?? []);
        }
        return $this->client;
    }

    /**
     * @param string $sourceText
     * @param string $source
     * @param string $target
     * @return string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function textTranslate(string $sourceText, string $source, string $target): ?string
    {
        $result = $this->request(['text' => $sourceText, 'from' => $source, 'to' => $target]);
        return $result['translation'][0]['translated'][0]['src-tokenized'] ?? null;
    }


    /**
     * @param array $params
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    private function request(array $params): array
    {
        $params = [
            'app_kid' => $this->appKid,
            'app_key' => $this->appKey,
            'text' => $params['text'] ?? '',
            'from' => $params['from'] ?? 'auto',
            'to' => $params['to'] ?? 'en',
        ];

        $body = (string) $this->getClient()->request('POST', $this->api, ['form_params' => $params])->getBody();
        return json_decode($body, true);
    }
}